package m3_publishsubscribe;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.UUID;

//发布和订阅模式---消费者
public class Consumer {

    public static void main(String[] args) throws Exception{

        //1.建立连接
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("192.168.64.140");
        cf.setPort(5672);
        cf.setUsername("admin");
        cf.setPassword("admin");

        Connection conn = cf.newConnection();
        Channel ch = conn.createChannel();

        //2.消费者定义队列（随机命名，非持久，独占，mq重启后自动删除队列）
        String queueName = UUID.randomUUID().toString();

        ch.queueDeclare(queueName,false,true,true,null);

        //3.定义交换机
        ch.exchangeDeclare("logs", BuiltinExchangeType.FANOUT);

        //4.将队列和交换机进行绑定
        //第3个参数，对于使用fanout交换机来说，写什么都无效
        ch.queueBind(queueName,"logs","");

        System.out.println("队列和交换机已绑定！");

        //5.1定义deliverCallback和cancelCallback
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String consumerTag, Delivery message) throws IOException {
                String msg = new String(message.getBody());
                System.out.println("收到消息： "+msg);
            }
        };

        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String consumerTag) throws IOException {
                //暂时啥都不写
            }
        };


        //5.消费者去消费（处理）数据
        ch.basicConsume(queueName,true, deliverCallback,cancelCallback);

    }



}
